package com.db.app;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.CharsetUtil;
import cn.hutool.core.util.StrUtil;
import com.db.utils.JdbcUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

public class Db2Csv {

    private static final Logger logger = LoggerFactory.getLogger(Db2Csv.class);

    private static List<String> csvDataList = new ArrayList<>(16);

    private static Properties properties;
    private static String configFile;
    private static String saveFile;

    public static void main(String[] args) {
        for (int i = 0; i < args.length; i++) {
            if ("--cf".equalsIgnoreCase(args[i])) {
                configFile = String.valueOf(args[i + 1]);
            } else if (("--sf".equalsIgnoreCase(args[i]))) {
                saveFile = String.valueOf(args[i + 1]);
            }
        }
        if (StrUtil.isEmpty(configFile) || StrUtil.isEmpty(saveFile)) {
            System.out.println("run as 'java -jar kingstar-sync-config.jar --cf XXX/db.properties --sf XXX/XXX.csv'");
            return;
        }
        properties = JdbcUtils.getProperties();

        readConfig(saveFile);
    }

    public static void readConfig(String filepath) {
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        //存储标题
        String[] fields = new String[0];
        logger.info("Start reading configuration table...");
        try {
            String url = properties.getProperty("url");
            String username = properties.getProperty("username");
            String password = properties.getProperty("password");
            String sql = properties.getProperty("sql");
            logger.info(String.format("connection info: url[%s] user[%s] pass[%s]", url, username, password));
            conn = JdbcUtils.getOracleConnection(url, username, password);
            ps = conn.prepareStatement(sql);
            rs = ps.executeQuery();
            boolean isFirst = true;
            while (rs.next()) {
                //标题赋值
                if (isFirst) {
                    ResultSetMetaData metaData = rs.getMetaData();
                    int columnCount = metaData.getColumnCount();
                    fields = new String[columnCount];
                    for (int i = 0; i < columnCount; i++) {
                        String columnName = metaData.getColumnName(i + 1);
                        fields[i] = columnName;
                    }
                    csvDataList.add(ArrayUtil.join(fields, ","));
                    isFirst = false;
                }

                StringBuilder value = new StringBuilder();
                for (String field : fields) {
                    Object data = rs.getObject(field);
                    value.append(data).append(",");
                }
                csvDataList.add(StrUtil.subBefore(value, ",", true));

            }
            FileUtil.writeLines(csvDataList, filepath, CharsetUtil.CHARSET_UTF_8);
            logger.info("Profile generated successfully! Path[{}]", filepath);
        } catch (Exception e) {
            logger.error("Profile generation failed,{}", e.getMessage(), e);
        } finally {
            JdbcUtils.close(rs, ps, conn);
        }
    }
}
